package com.realtyManage.springboot.Controller;

import com.alibaba.fastjson.JSON;
import com.realtyManage.springboot.Config.Wxacode;
import com.realtyManage.springboot.Model.Do.*;
import com.realtyManage.springboot.Model.Vo.*;
import com.realtyManage.springboot.Service.*;
import com.realtyManage.springboot.Utils.CoreUtils;
import com.realtyManage.springboot.Utils.SysExecRsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 杭州素色网络科技有限公司
 * 2019.08.08
 * 用户管理
 */

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    protected BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private IApplyInfoService applyInfoService;

    @Autowired
    private IIndexService indexService;

    @Autowired
    private IUserTaskService userTaskService;

    @Autowired
    private IFavouriteService favouriteService;

    @Autowired
    private IAnnouncementService announcementService;

    @Autowired
    private IChargeDetailService chargeDetailService;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IHulkService hulkService;

    @Autowired
    private IHulkTypeService hulkTypeService;

    @Autowired
    private IActiveService activeService;

    @Autowired
    private IHouseDetailService houseDetailService;

    @Autowired
    private IShopService shopService;

    @Autowired
    private ICustomerRegistrationService customerRegistrationService;

    @ResponseBody
    @RequestMapping("/userList")
    public String getList(UserEntity entity, HttpServletResponse response, HttpServletRequest request){
        return JSON.toJSONString(userService.findPagedByWhereClause(entity).getContent());
    }

    @ResponseBody
    @RequestMapping("/userinfo")
    public List<User> getAll(){
        return  userService.findAll();
    }

    //个人中心-获取用户基本信息
    @ResponseBody
    @RequestMapping("/center")
    public String getSelfInfo(HttpServletRequest request){
        UserEntity userEntity = new UserEntity();
        User user = userService.findByTelePhone(request.getSession().getAttribute("user").toString());
        //userEntity.setUid(user.getId());
        //userEntity.setName(user.getName());
        //userEntity.setImg(user.getImg());
        //userEntity.setShopId(user.getConnShopId());
        userEntity.setShopName(shopService.getOne(user.getConnShopId()).getName());
        //userEntity.setPhone(user.getTelephone());
        return JSON.toJSONString(userEntity);
    }


    @ResponseBody
    @RequestMapping("/census")
    public Map<String, String> census(HttpServletRequest request){
        User user = userService.findByTelePhone(request.getSession().getAttribute("user").toString());
        HashMap<String,String> map = new HashMap<>();

        int fullPhoneCust = customerService.countByConnUserIdAndType(user.getId(),1);
        int halfPhoneCust = customerService.countByConnUserIdAndType(user.getId(),2);
        int visitedCust = customerService.countByConnUserIdAndStatusNotAndStatusNot(user.getId(),1,6);

        map.put("totalCust",String.valueOf(fullPhoneCust+halfPhoneCust));
        map.put("fullPhoneCust",String.valueOf(fullPhoneCust));
        map.put("halfPhoneCust",String.valueOf(halfPhoneCust));
        map.put("visitedCust",String.valueOf(visitedCust));
        map.put("regTime",user.getRegTime().toString());
        map.put("joinTime",user.getJoinTime().toString());
        return map;
    }

    //------楼盘管理员开始-----
    @ResponseBody
    @RequestMapping(value = "/getManagementHouseInfo",method = RequestMethod.POST)
    private String getManagementHouseInfo(HttpServletRequest request) {
        String phone = request.getSession().getAttribute("user").toString();
        int manageHouseId = userService.findByTelePhone(phone).getManageHouseId();
        HouseDetail houseDetail = indexService.getHouseDetail(manageHouseId);
        return JSON.toJSONString(houseDetail);
    }
    //------楼盘管理员结束-----

    //文章列表
    @ResponseBody
    @RequestMapping(value = "/articleList",method = RequestMethod.GET)
    public String articleList(@RequestParam(value = "type", required=false)Integer type, @RequestParam("pageNumber")Integer pageNumber,@RequestParam("pageSize")Integer pageSize,HttpServletRequest request) {
        Page<Article> a = articleService.findPagedByTypeAndState(type,1,pageNumber,pageSize);
        return JSON.toJSONString(articleService.findPagedByTypeAndState(type,1,pageNumber,pageSize));
    }

    //文章详情
  /*  @ResponseBody
    @RequestMapping(value = "/articleDetail/{artId}",method = RequestMethod.GET)
    public String articleDetail(@PathVariable Integer artId,HttpServletRequest request) {
        return JSON.toJSONString(articleService.getOne(artId));
    }*/
  //设置咨讯为首页展示
    @ResponseBody
    @RequestMapping(value = "/setHomePage",method = RequestMethod.POST)
    public String articleList(Article article,HttpServletRequest request) {
        Integer code = -1;
        BaseEntity baseEntity = new BaseEntity();
        if (article.getIsExhibition() == null && article.getIsExhibition() == ' '){
            article.setIsExhibition(0);
        }
        if (articleService.update(article) > 0){
            code = 1;
        }
        baseEntity.setInfoCode(code);
        baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(baseEntity);
    }

    //参加活动
    @ResponseBody
    @RequestMapping(value = "/takePartIn",method = RequestMethod.POST)
    public String articleList(HttpServletRequest request) {
        int artId = Integer.parseInt(request.getParameter("artId"));
        String userName = request.getParameter("userName");
        String phone = request.getParameter("phone");
        String level = request.getParameter("level");
        String type = request.getParameter("type");
        String userId = request.getParameter("userId");

        Date d = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String x = df.format(d);
        //获取活动信息
        List<Article> articleList = articleService.findByEndTimeAndRegion(artId);
        for (int i =0;i< articleList.size();i++){
            String endTime = (articleList.get(i).getEndTime()).toString();
            String region = articleList.get(i).getRegion();
            // 判断活动时间是否过期
            if(x.compareTo(endTime) > 0){
                BaseEntity baseEntity = new BaseEntity();
                baseEntity.setInfoCode(-4396);
                baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(-4396));
                return JSON.toJSONString(baseEntity);
            }
            //超级奖励判断是否符合权限设计   分销聚会则不判断
            if (!type.equals("2")){   //2 分销聚会
                String[] regions = region.split(",");
                for (String qx : regions) {
                    if (!qx.equals(level)){
                        BaseEntity baseEntity = new BaseEntity();
                        baseEntity.setInfoCode(101);
                        baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(101));
                        return JSON.toJSONString(baseEntity);
                    }
                }
                //是否满足条件1
                String one = "0"; //判定条件1
                String two = "0"; //判断条件2
                if (one.equals("1") || two.equals("1")){
                    BaseEntity baseEntity = new BaseEntity();
                    baseEntity.setInfoCode(-1032);
                    baseEntity.setInfoText(SysExecRsUtil.getMsgFromCode(-1032));
                    return JSON.toJSONString(baseEntity);
                }
            }
        }
        Integer uid = userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId();
        //用手机号查询用户信息
        if (uid == null){   //此用户不在系统中或未登录
            if (userService.findByTelePhone(phone).getId() != null){   //存在系统中但未登录
                uid = userService.findByTelePhone(phone).getId();
            }else{    //不存在系统中则自行录入系统
                User user = new User();
                user.setTelephone(phone);
                user.setName(userName);
                user.setIntegral(0); //没有积分
                user.setPwd(bCryptPasswordEncoder.encode("123456")); //默认密码
                user.setLevel(1);
                user.setStatus(1);
                user.setRegTime(new Date());
                Integer id = userService.insert(user).getId();
                if(uid != null){
                    uid = id;
                }
            }
        }
        int code = activeService.takePartIn(uid,artId);
        BaseEntity entity = new BaseEntity();
        entity.setInfoCode(code);
        entity.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(entity);
    }

    //获客海报大类
    @ResponseBody
    @RequestMapping(value = "/hulkTypeList",method = RequestMethod.GET)
    public String hulkTypeList(HttpServletRequest request) {
        return JSON.toJSONString(hulkTypeService.findAll());
        //return JSON.toJSONString(hulkService.findDistinctType());
    }

    //获客海报
    @ResponseBody
    @RequestMapping(value = "/hulkList",method = RequestMethod.GET)
    public String hulkList(@RequestParam Integer pageNumber,@RequestParam Integer pageSize, HttpServletRequest request) {
        String type = request.getParameter("type");
        return JSON.toJSONString(hulkService.findPagedByType(type,pageNumber,pageSize));
    }

    /**
     * 收藏
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/favourite")
    public String favourite(HttpServletRequest request){
        BaseEntity entity = new BaseEntity();
        int uid = Integer.parseInt(request.getParameter("uid"));
        if (request.getMethod().equals("POST")) {
            int operateCode = Integer.parseInt(request.getParameter("operateCode"));//1.收藏 2.取消
            Favourite favourite = new Favourite();
            if(operateCode==1){
                int connHouseId = Integer.parseInt(request.getParameter("connHouseId"));
                if(favouriteService.findByConnUserIdAndConnHouseIdAndState(uid,connHouseId,operateCode)!=null){
                    entity.setInfoCode(-1021);
                    entity.setInfoText(SysExecRsUtil.getMsgFromCode(-1021));
                    return JSON.toJSONString(entity);
                }
                favourite.setConnUserId(uid);
                favourite.setConnHouseId(connHouseId);
                favourite.setInsertDate(new Date());
                favourite.setState(operateCode);
            }else{
                int favId = Integer.parseInt(request.getParameter("favId"));
                favourite = favouriteService.getOne(favId);
                favourite.setState(operateCode);
            }

            if(favouriteService.save(favourite)!=null){
                entity.setInfoCode(1);
                entity.setInfoText(SysExecRsUtil.getMsgFromCode(1));
            }else{
                entity.setInfoCode(-1);
                entity.setInfoText(SysExecRsUtil.getMsgFromCode(-1));
            }
            return JSON.toJSONString(entity);
        } else {
            HashMap<String,Object> map = new HashMap<>();
            List<Favourite> favouriteList = favouriteService.getMyFavouriteList(uid);
            List<FavEntity> FavEntityList = new ArrayList<>();
            for(Favourite favourite:favouriteList){
                FavEntity favEntity = new FavEntity();
                favEntity.setFavId(favourite.getId());
                favEntity.setHouseDetail(indexService.getHouseDetail(favourite.getConnHouseId()));
                FavEntityList.add(favEntity);
            }
            return JSON.toJSONString(FavEntityList);
        }
    }

    @ResponseBody
    @RequestMapping("/checkFavourite")
    public boolean checkFavourite(HttpServletRequest request){
        int uid = Integer.parseInt(request.getParameter("uid"));
        int connHouseId = Integer.parseInt(request.getParameter("connHouseId"));
        if(favouriteService.findByConnUserIdAndConnHouseIdAndState(uid,connHouseId,1)!=null){
            return true;
        }else{
            return false;
        }
    }

    @ResponseBody
    @RequestMapping("/generateInviteCode")
    public String generateInviteCode(UserEntity entity, HttpServletRequest request){
        String inviteCode="";
        if(Integer.parseInt(request.getSession().getAttribute("level").toString()) > 1){
            inviteCode = CoreUtils.generateRandomCode(7);
            User user = userService.findById(entity.getUid());
            user.setInviteCode(inviteCode);
            userService.updateUserInfo(user);
        }else{
            //越权
        }
        return inviteCode;
    }

    @ResponseBody
    @RequestMapping(value="/generateQrCode",produces="text/plain;charset=UTF-8")
    public String generateQrCode(HttpServletRequest request){
        String appid = request.getParameter("appid");
        String secret = request.getParameter("secret");
        String customScene = request.getParameter("customScene");
        if(appid!=null&&secret!=null&&customScene!=null){
            return Wxacode.getWxacode(appid,secret,customScene);
        }
        return null;
    }


    /**
     * 获取报备需审批数据
     * @param userId
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getCustomerList",method = RequestMethod.GET)
    public String getCustomerList(@RequestParam String userId,@RequestParam String level,HttpServletRequest request) {
        User user = userService.findById(Integer.valueOf(userId));
        Integer houseId = user.getManageHouseId();
        List<Customer>  ct = customerService.getCustomerList(houseId,level);
        List<CustomerEntity> list = new ArrayList<>();
        if (ct.size() > 0){
            for (int i=0;i<ct.size();i++){
                CustomerEntity ce = new CustomerEntity();
                ce.setCustomerId(ct.get(i).getId());
                ce.setTelephone(ct.get(i).getTelephone());
                ce.setConnUid(ct.get(i).getConnUserId());
                ce.setUserName(userService.findByName(ct.get(i).getConnUserId()));
                //ce.setSex(Integer.valueOf(userService.findBySex(ct.get(i).getSex())));
                ce.setConnHouseId(ct.get(i).getConnHouseId());
                ce.setHouseName(userService.findByHouseName(ct.get(i).getConnHouseId()));
                ce.setDescription(ct.get(i).getOrderDescription());
                ce.setInsertTime(ct.get(i).getInsertDate());
                ce.setName(ct.get(i).getName());
                list.add(ce);
            }
        }
        return JSON.toJSONString(list);
    }

    /**
     * 修改报备审核状态
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateReportedType",method = RequestMethod.POST)
    private String updateReportedType(HttpServletRequest request) {
        String customerId = request.getParameter("customerId");
        String userId = request.getParameter("userId");
        String userName =userService.findByName(Integer.valueOf(userId));
        String reportedType = request.getParameter("reportedType");
        RegEntity regInfo = new RegEntity();
        Date approvalTime = new Date();
        int count = customerService.updateReportedType(customerId,userName,userId,approvalTime,reportedType);
        if (count > 0){
            //报备最终成功
            Announcement announcement = new Announcement();
            User user = userService.findByTelePhone(request.getSession().getAttribute("user").toString());
            String name = customerService.getName(customerId);
         String title = "";
            Integer type = null;
            if(user.getLevel()==4){//门店
                title = user.getName()+"门店负责人报备"+name+"客户一名";
                type = 2;
            }
            if(user.getLevel()==3){//经纪人
                title = user.getName()+"门店经纪人报备"+name+"客户一名";
                type = 3;
            }
            if(user.getLevel()==2){//独立
                title = user.getName()+"独立经纪人报备"+name+"客户一名";
                type = 4;
            }
            announcement.setTitle(title);
            announcement.setType(type);
            announcement.setTime(new Date());
            announcement.setState(1);
            announcementService.insert(announcement);

            regInfo.setInfoCode(1);
            regInfo.setInfoText(SysExecRsUtil.getMsgFromCode(1));
        }else{
            regInfo.setInfoCode(-1);
            regInfo.setInfoText(SysExecRsUtil.getMsgFromCode(-1));
        }
        return JSON.toJSONString(regInfo);
    }

    /**
     * 用户列表角色
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getLevelUserList",method = RequestMethod.GET)
    private String getLevelUserList(HttpServletRequest request){
        String level = request.getParameter("level");
        String type = request.getParameter("type");
        List<User> list  = userService.findLevelUserList(level,type,request);
        return  JSON.toJSONString(list);
    }


    /**
     * 新增修改任务
     * @param userTask
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/insertTask",method = RequestMethod.POST)
    private String insertTask(UserTask userTask,HttpServletRequest request) {
        userTask.setDistributionUserId(userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId().toString());
        Integer code = -1;
        RegEntity regInfo = new RegEntity();
        if (userTaskService.insert(userTask) > 0){
            code = 1;
        }
        regInfo.setInfoCode(code);
        regInfo.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(regInfo);
    }


    /**
     * 查询任务列表
     * @param userTaskEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getTaskList",method = RequestMethod.GET)
    private String getTaskList(UserTaskEntity userTaskEntity,HttpServletRequest request){
        userTaskEntity.setDistributionUserId(userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId().toString());
        return  JSON.toJSONString(userTaskService.findPagedByWhereClause(userTaskEntity));
    }


    /**
     * 删除任务
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteTask",method = RequestMethod.POST)
    private String deleteTask(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        Integer code = -1;
        RegEntity regInfo = new RegEntity();
        if (userTaskService.deleteTask(ids) > 0){
            code = 1;
        }
        regInfo.setInfoCode(code);
        regInfo.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(regInfo);
    }

    /**
     * 任务审批
     * @param userTask
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/examine",method = RequestMethod.POST)
    private String examine(UserTask userTask,HttpServletRequest request) {
        Integer code = -1;
        RegEntity regInfo = new RegEntity();
        if (userTaskService.update(userTask) > 0){
            code = 1;
        }
        regInfo.setInfoCode(code);
        regInfo.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(regInfo);
    }

    @ResponseBody
    @RequestMapping(value = "/houseMarketingControl",method = RequestMethod.GET)
    private String houseMarketingControl(UserTaskEntity userTaskEntity,HttpServletRequest request){
        return  JSON.toJSONString(houseDetailService.houseMarketingControl(userTaskEntity));
    }

    /**
     * 修改密码
     * @param userEntity
     * @param request
     * @return
     */
    @RequestMapping(value = "/updatePwd",method = RequestMethod.POST)
    @ResponseBody
    private String updatePwd(UserEntity userEntity,HttpServletRequest request) {
        BaseEntity be = new BaseEntity();
        BCryptPasswordEncoder en = new BCryptPasswordEncoder();
        Integer code = -1;
        User u = userService.findByTelePhone(userEntity.getPhone());
        String oldPwd = u.getPwd();
        if (en.matches(userEntity.getNewPwd(),oldPwd)){
            code = -4999;
        }else{
            userEntity.setPwd(en.encode(userEntity.getNewPwd()));
            int value = userService.updatePwd(userEntity);
            if (value > 0){
                code = 1;
            }
        }
        be.setInfoCode(code);
        be.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(be);
    }


    /**
     * 修改个人信息
     * @param user
     * @param response
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateMyDetail",method = RequestMethod.POST)
    public String updateMyDetail(User user,HttpServletResponse response, HttpServletRequest request){
        Integer code = -1;
        BaseEntity be = new BaseEntity();
        user.setId(userService.findByTelePhone(request.getSession().getAttribute("user").toString()).getId());
        if (userService.updateMyDetail(user) > 0){
            code = 1;
        }
        be.setInfoCode(code);
        be.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(be);
    }


    /**
     * 修改置业顾问前端显示问题
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateShow",method = RequestMethod.POST)
    public String updateShow(User user){
        Integer code = -1;
        BaseEntity be = new BaseEntity();
        if (userService.updateMyDetail(user) > 0){
            code = 1;
        }
        be.setInfoCode(code);
        be.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(be);
    }


    /**
     * 冻结用户
     * @param user
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/frozenUser",method = RequestMethod.POST)
    public String frozenUser(User user,HttpServletRequest request){
        String frozen = request.getParameter("frozen");  //-1 冻结  1正常
        user.setStatus(Integer.valueOf(frozen));
        Integer code = -1;
        BaseEntity be = new BaseEntity();
        if (userService.updateMyDetail(user) > 0){
            code = 1;
        }
        be.setInfoCode(code);
        be.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(be);
    }

    /**
     * 验证用户是否冻结
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/verificationUser",method = RequestMethod.GET)
    public String verificationUser(HttpServletRequest request){
        String userName = request.getParameter("userName");  //用户登录名
        Integer code = -1;
        BaseEntity be = new BaseEntity();
        if (userService.verificationUser(userName) > 0){
            code = 1;
        }
        be.setInfoCode(code);
        be.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(be);
    }

    /**
     * 转移用户的客户信息
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/transferUser",method = RequestMethod.POST)
    public String transferUser(HttpServletRequest request){
        Integer code = -1;
        String inputUser = request.getParameter("inputUser");  //冻结用户
        String outUser = request.getParameter("outUser"); //接手用户
        BaseEntity be = new BaseEntity();
        if (customerRegistrationService.transferUser(inputUser,outUser) > 0){
            //houseDetailService.transferUser(inputUser,outUser);
            code = 1;
        }
        be.setInfoCode(code);
        be.setInfoText(SysExecRsUtil.getMsgFromCode(code));
        return JSON.toJSONString(be);
    }



}
